/** 创建全局state和上下文关系组件*/
import React from "react";
import { useState } from "react";

interface AppStateValue {
  username: string;
  shoppingCart: {
    items: { id: string; name: string }[]; // 是一个数组
  };
}

// 全局数据传递
const defaultContextValue: AppStateValue = {
  username: "汪苏泷",
  shoppingCart: {
    items: [],
  },
};

// todo 抄写高阶组件的例子还有自定义hook的例子

export const appContext = React.createContext(defaultContextValue); // 传入默认值
// setstate的全局上下文 设置泛型类型
export const appSetStateContext = React.createContext<
  React.Dispatch<React.SetStateAction<AppStateValue>> | undefined
>(undefined);

export const AppStateProvider: React.FC<{ children }> = (props) => {
  const [state, setState] = useState(defaultContextValue);

  return (
    <appContext.Provider value={state}>
      <appSetStateContext.Provider value={setState}>
        {props.children}
      </appSetStateContext.Provider>
    </appContext.Provider>
  );
};
